﻿namespace ClassyBlog.DataAccess
{
    using System;
    using System.Collections.Generic;
    using System.Linq;

    using DomainObjects;
    using ExtensionMethods;
    using Infrastructure;

    public class PostFactory : ArticleFactory<Post>
    {
        private static readonly
            IDictionary<string, Action<Post, string, object>> setters =
            BuildSetters();

        public PostFactory(IFileSystem fileSystem) : base(fileSystem)
        {
        }

        protected override Post CreateLazy(string dataPath, string filePath)
        {
            var loader = new LazyArticleLoader<Post>(filePath, FileSystem, setters);

            var post = new LazyPost(loader);

            return post;
        }

        private static IDictionary<string, Action<Post, string, object>>
            BuildSetters()
        {
            return new Dictionary<string, Action<Post, string, object>>
                       {
                           {
                               "Tags",
                               (post, property, value) =>
                                {
                                    var list = value as IEnumerable<string>;
                                    var hash = value as
                                        IDictionary<string, string>;

                                    if (list != null)
                                    {
                                        list.Distinct(
                                            StringComparer.OrdinalIgnoreCase)
                                            .Each(tag =>
                                                post.Tags.Add(new Tag
                                                {
                                                  Title = tag,
                                                  Slug = tag
                                                }));
                                    }
                                    else if (hash != null)
                                    {
                                        hash.Each(tag =>
                                            post.Tags.Add(new Tag
                                            {
                                                Title = tag.Key,
                                                Slug = tag.Value
                                            }));
                                    }
                                }
                           }
                       };
        }
    }
}